package com.atguigu.gmall.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

public class DimUtil {

    public static JSONObject getDimInfo(Connection connection, String tableName, String key) throws Exception {

        //先查询Redis
        Jedis jedis = JedisUtil.getJedis();
        String redisKey = "FLINK-REALTIME:DIM:" + tableName + ":" + key;
        String dimJsonStr = jedis.get(redisKey);

        //! 如果在Redis缓存中 存在要查找的数据
        if (dimJsonStr != null) {
            // 重置过期时间
            jedis.expire(redisKey, 24 * 60 * 60);
            // 归还连接
            jedis.close();
            // 返回维度数据
            return JSON.parseObject(dimJsonStr);
        }

        //! 如果在Redis缓存中 不存在要查找的数据
        //! 就去Phoenix中查找数据
        //拼接SQL语句
        String querySql = "select * from " + MyConfig.HBASE_SCHEMA + "." + tableName + " where id='" + key + "'";
        System.out.println("querySql>>>" + querySql);

        //查询数据
        List<JSONObject> queryList = JdbcUtil.queryList(connection, querySql, JSONObject.class, false);

        //? 将从Phoenix查询到的数据写入Redis
        JSONObject dimInfo = queryList.get(0);
        jedis.set(redisKey, dimInfo.toJSONString());
        //设置过期时间
        jedis.expire(redisKey, 24 * 60 * 60);
        //归还连接
        jedis.close();

        //返回结果
        return dimInfo;
    }

    /**
     * 删除Redis中存储的维度数据
     *! 需要在向Phoenix中写入同步MySQL维度表数据的时候，判断由MaxWell同步的维度表数据的type == update?
     *! 如果为update，说明Redis中缓存的维度表数据发生了改变，需要删除Redis中缓存的该条数据，重新向Phoenix查询数据并写入Redis缓存中
     * @param tableName 表名
     * @param key 主键id
     */
    public static void delDimInfo(String tableName, String key) {
        //获取连接
        Jedis jedis = JedisUtil.getJedis();
        //删除数据
        String redisKey = "FLINK-REALTIME:DIM:" + tableName + ":" + key;
        jedis.del(redisKey);
        //归还连接
        jedis.close();
    }

    public static void main(String[] args) throws Exception {

        DruidDataSource dataSource = DruidDSUtils.createDataSource();
        DruidPooledConnection connection = dataSource.getConnection();

        long start = System.currentTimeMillis();
        JSONObject dimInfo = getDimInfo(connection, "DIM_BASE_TRADEMARK", "11");
        long end = System.currentTimeMillis();
        JSONObject dimInfo2 = getDimInfo(connection, "DIM_BASE_TRADEMARK", "11");
        long end2 = System.currentTimeMillis();

        System.out.println(dimInfo);
        System.out.println(dimInfo2);

        System.out.println(end - start);  // 159  127  120  127  121  122  119
        System.out.println(end2 - end);   // 8  8  8  1  1  1  1  0  0.5

        connection.close();

    }

}
